package com.hmall.trade.listener;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hmall.api.client.item.ItemClient;
import com.hmall.api.client.pay.PayClient;
import com.hmall.api.dto.OrderDetailDTO;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.common.constants.MqConstants;
import com.hmall.common.utils.BeanUtils;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.domain.po.OrderDetail;
import com.hmall.trade.service.IOrderDetailService;
import com.hmall.trade.service.IOrderService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class OrderDelayMessageListener {
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderDetailService orderDetailService;
    @Autowired
    private PayClient payClient;
    @Autowired
    private ItemClient itemClient;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(MqConstants.DELAY_ORDER_QUEUE_NAME),
            exchange = @Exchange(value = MqConstants.DELAY_EXCHANGE_NAME,delayed = "true", type = ExchangeTypes.DIRECT),
            key = MqConstants.DELAY_ORDER_KEY
    ))
    public void listener(Long orderId){
        Order order = null;
        order = orderService.getById(orderId);
        if(order == null || order.getStatus()!=1){
            return;
        }
        //查询支付单
        PayOrderDTO payOrderDTO = payClient.queryPayOrderByBizOrderNo(orderId);
        //支付单状态为已支付，修改订单状态为已支付
        if(payOrderDTO.getStatus() == 3){
            order.setStatus(2);
            orderService.updateById(order);
            return;
        }
        //支付单状态为未支付，修改订单状态为“交易取消，订单关闭”,撤回减少库存操作
        order.setStatus(5);
        orderService.updateById(order);
        List<OrderDetail> list = orderDetailService.list(Wrappers.<OrderDetail>lambdaQuery().eq(OrderDetail::getOrderId,orderId));
        List<OrderDetailDTO> dtoList = BeanUtils.copyList(list, OrderDetailDTO.class);
        dtoList.forEach(d->{
            d.setNum(Math.negateExact(d.getNum()));
        });
        itemClient.deductStock(dtoList);
    }
}
